import styles from './index.module.scss'
import Icon from '@/components/Icon'
import NavBar from '@/components/NavBar'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getArticleDetail } from '@/store/action/article'
import { useParams } from 'react-router'
import { RootState } from '@/store'
import { sanitize } from 'dompurify'
import dayjs from 'dayjs'
import Skeleton from './components/Skeleton'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import ArticleFooter from './components/ArticleFooter'
import NoComment from './components/NoComment'
import CommentItem from './components/CommentItem'
import { getComments } from '@/store/action/comment'

export default function Article() {
  const dispatch = useDispatch()

  // 🔔 useParams 函数需要指定泛型确定 params 对象的格式
  const params = useParams<{ id: string }>()
  // console.log(params.id)

  const { detail } = useSelector((state: RootState) => state.article)
  const { comments } = useSelector((state: RootState) => state.comment)

  useEffect(() => {
    // 获取文章的详情
    dispatch(getArticleDetail(params.id))
    // 获取文章的评论列表
    dispatch(getComments({ source: params.id }))
  }, [dispatch, params.id])

  useEffect(() => {
    // 文章还没加载完毕，先不处理
    if (!detail.art_id) return
    // console.log('加载完毕了，需要高亮处理', detail.art_id)
    // 配置 highlight.js
    hljs.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true,
    })

    // 查找容器元素下符合 pre code 选择器规则的子元素，进行高亮
    const codes = document.querySelectorAll('.dg-html pre')
    if (codes.length > 0) {
      return codes.forEach((el: any) => hljs.highlightElement(el))
    }
  }, [detail.art_id])

  const [showAuthor, setShowAuthor] = useState(false)
  // 作者信息 DOM
  const authorRef = useRef<HTMLDivElement>(null)
  // 滚动事件处理函数
  const handleScroll = () => {
    // 获取元素在可视区的滚动距离
    if (authorRef.current!.getBoundingClientRect().y < 0) {
      setShowAuthor(true)
    } else {
      setShowAuthor(false)
    }
  }

  const wrapperRef = useRef<HTMLDivElement>(null)
  const commemtHeadRef = useRef<HTMLDivElement>(null)
  const onShowComment = () => {
    // console.log('需要滚动到评论区')
    // console.log(wrapperRef.current?.scrollTop)
    // console.log(commemtHeadRef.current!)
    wrapperRef.current?.scrollTo({
      top:
        commemtHeadRef.current!.offsetTop -
        commemtHeadRef.current!.offsetHeight,
    })
  }

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        {/* 顶部导航栏 */}
        <NavBar right={<Icon type="icongengduo" />}>
          {showAuthor ? (
            <div className="nav-author">
              <img src={detail.aut_photo} alt="" />
              <span className="name">{detail.aut_name}</span>
              <span className="follow">关注</span>
            </div>
          ) : (
            <>文章详情</>
          )}
        </NavBar>
        {/* 文章主体 */}
        <div className="wrapper" ref={wrapperRef} onScroll={handleScroll}>
          <div className="article-wrapper" hidden={!!detail.art_id}>
            {/* 骨架屏占位效果 */}
            <Skeleton />
          </div>
          <div className="article-wrapper" hidden={!detail.art_id}>
            {/* 文章描述信息栏 */}
            <div className="header">
              <h1 className="title">{detail.title}</h1>

              <div className="info">
                <span>
                  {dayjs(detail.pubdate).format('YYYY-MM-DD hh:mm:ss')}
                </span>
                <span>{10} 阅读</span>
                <span>{detail.comm_count} 评论</span>
              </div>

              {/* 作者信息 - 滚动出去到可视区外，头部显示作者信息*/}
              <div className="author" ref={authorRef}>
                <img src={detail.aut_photo} alt="" />
                <span className="name">{detail.aut_name}</span>
                <span className="follow">关注</span>
              </div>
            </div>

            {/* 文章正文内容区域 */}
            <div className="content">
              <div
                className="content-html dg-html"
                // 💥 dompurify.sanitize() 对 HTML 内容进行净化，防止 XSS 攻击
                dangerouslySetInnerHTML={{ __html: sanitize(detail.content) }}
              />
              <div className="date">
                发布文章时间：
                {dayjs(detail.pubdate).format('YYYY-MM-DD hh:mm:ss')}
              </div>
            </div>
            <div className="divider"></div>
            <div className="comment">
              {/* 评论总览信息 */}
              <div className="comment-header" ref={commemtHeadRef}>
                <span>全部评论（{detail.comm_count}）</span>
                <span>{detail.like_count} 点赞</span>
              </div>

              {/* 评论列表 */}
              {comments.results?.length === 0 ? (
                <NoComment />
              ) : (
                comments.results?.map((item) => (
                  <CommentItem key={item.com_id} comment={item} />
                ))
              )}
            </div>
          </div>
        </div>
        {/* 文章底部 */}
        <ArticleFooter onShowComment={onShowComment} />
      </div>
    </div>
  )
}
